
package com.th.supcom.pds.recipefee.client.business;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.KeyNav;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.pds.common.client.commom.PdsAuditPrescServiceFactory;
import com.th.supcom.pds.common.client.model.PdsSupplyModel;
import com.th.supcom.pds.common.constant.KeysConstants;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.internal.client.model.ResultModel;
import com.th.supcom.pds.prescstatusquery.client.widget.SupplyStatusQueryWindow;
import com.th.supcom.pds.recipefee.client.common.RecipeFeeModuleEvents;
import com.th.supcom.pds.recipefee.client.service.RecipeFeeRpcAsync;
import com.th.supcom.pds.recipefee.client.widget.RecipeFeeFields;
import com.th.supcom.pds.recipefee.client.widget.RecipeFeeMainPanel;
import com.th.supcom.pds.recipefee.client.widget.RecipeFeeUtils;
import com.th.supcom.pds.sortingdrug.client.model.PdsPrescDetailInfoModel;

/**
 * 收方收费业务处理
 */
public final class RecipeFeeBusiness
{
    /**
     * 公司版权信息.
     */
    public static final String copyright = "Copyright 2014, Carefx Corporation";
    private static final RecipeFeeRpcAsync S_RECIPE_FEE_RPC_ASYNC = PdsAuditPrescServiceFactory.getRecipeFeeService ();
    /**
     * 提交路径.
     */
    public static final String SCC_BRANCH = "$URL$";

    /**
     * 提交日期.
     */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /**
     * 最终修改人员.
     */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /**
     * 最终版本号.
     */
    public static final String SCC_REVISION = "$Revision$";

    private static void closeWindow (final PdsSupplyModel currentCondition, final Component component)
    {
        final SupplyStatusQueryWindow window = new SupplyStatusQueryWindow (currentCondition);
        window.show ();
        new KeyNav <ComponentEvent> (window)
        {
            @Override
            public void onKeyPress (final ComponentEvent ce)
            {
                final int keyCode = ce.getKeyCode ();
                if (ce.isAltKey () && keyCode == KeysConstants.VK_C)
                {// 关闭窗体
                    window.hide ();
                    component.focus ();
                }
            }
        };
    }

    public static void confirm (final RecipeFeeMainPanel mainPanel, final Map <String, Object> map)
    {
        final List <PdsPrescDetailInfoModel> prescs = mainPanel.getRecipePanel ().getGrid ().getSelectionModel ()
                                                               .getSelectedItems ();
        // 得到选中的处方对应的明细
        if (prescs.isEmpty ())
        {
            ClientUtils.alertMessageBox ("请选择要确认的信息", null);
            return;
        }
        MessageBox.confirm ("警告", "是否确认收方", new Listener <MessageBoxEvent> ()
        {
            @Override
            public void handleEvent (final MessageBoxEvent be)
            {
                final Button btn = be.getButtonClicked ();
                if (Dialog.YES.equals (btn.getItemId ()))
                {
                    final List <PdsPrescDetailInfoModel> prescsDetails = mainPanel.getPrescDetailGrid ().getGrid ()
                                                                                  .getStore ().getModels ();
                    // 对处方进行确认检查
                    for (final PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescsDetails)
                    {
                        // 库存确认
                        if (pdsPrescDetailInfoModel.getStockFlag () != null)
                        {
                            ClientUtils.alertMessageBox ("库存不足", null);
                            return;
                        }
                    }
                    // 对处方，以及处方明细进行持久化操作
                    RecipeFeeBusiness.confrim (prescs, prescsDetails, map);
                }
            }
        });

    }

    public static void loadData (RecipeFeeMainPanel mainPanel)
    {
        final Grid <PdsPrescDetailInfoModel> grid = mainPanel.getPrescDetailGrid ().getGrid ();
        final CheckBoxSelectionModel <PdsPrescDetailInfoModel> checkmodel = mainPanel.getRecipePanel ()
                                                                                     .getCheckmodel ();
        final PdsPrescDetailInfoModel selectedPresc = checkmodel.getSelectedItem ();
        String currentDispensary = ClientUtils.getOrgModel ().getOrgCode ();
        // 通过选中的主记录得到对应的明细
        RecipeFeeBusiness.S_RECIPE_FEE_RPC_ASYNC.findPrescDetailInfoByPrescNo (selectedPresc,
                                                                               currentDispensary,
                                                                               new AsyncCallback <List <PdsPrescDetailInfoModel>> ()
                                                                               {

                                                                                   @Override
                                                                                   public void onFailure (Throwable caught)
                                                                                   {
                                                                                       ClientUtils.alertMessageBox (caught.getLocalizedMessage (),
                                                                                                                    null);
                                                                                   }

                                                                                   @Override
                                                                                   public void onSuccess (List <PdsPrescDetailInfoModel> result)
                                                                                   {
                                                                                       if(result.isEmpty ()){
                                                                                           return;
                                                                                       }
                                                                                       for (PdsPrescDetailInfoModel pdsPrescDetailInfoModel : result)
                                                                                    {
                                                                                        if("1".equals (pdsPrescDetailInfoModel.getCheckFlag ())){
                                                                                            checkmodel.deselect (pdsPrescDetailInfoModel);
                                                                                            MessageBox.info ("提示", "该处方需要审核", null);
                                                                                            return;
                                                                                        }
                                                                                    }
                                                                                       grid.getStore ().add (result);
                                                                                   }
                                                                               });
    }

    /**
     * 通过处方号查询处方明细
     * 
     * @param prescField
     * @param time
     * @param prescDetailGrid
     * @param prescGrid add by Zli
     */
    @SuppressWarnings ("deprecation")
    public static void queryByPrescNo (Map <String, Object> map, final RecipeFeeMainPanel mainpanel)
    {
        RecipeFeeFields fields = mainpanel.getFields ();
        final Date startTime = fields.getStartField ().getValue ();
        startTime.setHours (0);
        startTime.setMinutes (0);
        startTime.setSeconds (0);
        final Date endTime = fields.getEndField ().getValue ();
        endTime.setHours (59);
        endTime.setMinutes (59);
        endTime.setSeconds (59);
        if ((Integer) map.get ("flag") == 1 && fields.getRecipeNoField ().getValue () == null)
        {
            ClientUtils.alertMessageBox ("请输入处方号", fields.getRecipeNoField ());
            return;
        }
        mainpanel.mask ("正在拼命加载中");
        // 根据处方号查询患者信息
        map.put ("beginDate", startTime);
        map.put ("endDate", endTime);
        map.put ("prescNo", fields.getRecipeNoField ().getValue ());
        queryByCondition (mainpanel, map);

    }

    /**
     * 刷卡得到患者信息和处方信息
     * 
     * @param patientId
     * @param enterTime
     * @param mainpanel add by Zli
     */
    @SuppressWarnings ("deprecation")
    public static void queryByCardNo (Map <String, Object> map, final RecipeFeeMainPanel mainpanel)
    {
        RecipeFeeFields fields = mainpanel.getFields ();
        final Date startTime = fields.getStartField ().getValue ();
        startTime.setHours (0);
        startTime.setMinutes (0);
        startTime.setSeconds (0);
        final Date endTime = fields.getEndField ().getValue ();
        endTime.setHours (59);
        endTime.setMinutes (59);
        endTime.setSeconds (59);
        String dispensaryCode = ClientUtils.getOrgModel ().getOrgCode ();
        map.put ("beginDate", startTime);
        map.put ("endDate", endTime);
        map.put ("dispensaryCode", dispensaryCode);

        // 刷卡不需进行各个处方验证
        queryByCondition (mainpanel, map);
    }

    /**
     * 保存确认数据
     * 
     * @param prescs
     * @param models
     * @param operator
     */
    private static void confrim (final List <PdsPrescDetailInfoModel> prescs,
                                 final List <PdsPrescDetailInfoModel> models, Map <String, Object> map)
    {
        RecipeFeeBusiness.S_RECIPE_FEE_RPC_ASYNC.confrimRecipe (prescs, models, map, new AsyncCallback <Map <String, Object>> ()
        {

            @Override
            public void onFailure (final Throwable caught)
            {
                ClientUtils.alertMessageBox (caught.getMessage (), null);
            }

            @Override
            public void onSuccess (final Map <String, Object> result)
            {
                Info.display ("提示", "收方 收费成功");
                // 开始调用前台打印组件进行打印
                AppEvent event = new AppEvent (RecipeFeeModuleEvents.RECIPEFEE_PRINT);
                event.setData ("result",result);
                Dispatcher.forwardEvent (event);
            }
        });
    }

    private static void verifyPresc (final String prescNo, final TextField <String> prescField)
    {
        PdsAuditPrescServiceFactory.getPdsPrescDetailService ()
                                   .getPrescDetailByPrescAndRcpt (null, prescNo,
                                                                  new AsyncCallback <List <PdsPrescDetailInfoModel>> ()
                                                                  {

                                                                      @Override
                                                                      public void onFailure (final Throwable caught)
                                                                      {
                                                                          ClientUtils.alertMessageBox (caught.getMessage (),
                                                                                                       prescField);
                                                                          final AppEvent event = new AppEvent (
                                                                                                               RecipeFeeModuleEvents.RECIPEFEE_CLEAR);
                                                                          Dispatcher.forwardEvent (event);
                                                                          return;

                                                                      }

                                                                      @Override
                                                                      public void onSuccess (final List <PdsPrescDetailInfoModel> result)
                                                                      {
                                                                          if (result == null)
                                                                          {
                                                                              ClientUtils.alertMessageBox ("该处方号不存在,请重新输入",
                                                                                                           prescField);
                                                                              final AppEvent event = new AppEvent (
                                                                                                                   RecipeFeeModuleEvents.RECIPEFEE_CLEAR);
                                                                              Dispatcher.forwardEvent (event);
                                                                              return;
                                                                          }
                                                                          final PdsSupplyModel currentCondition = new PdsSupplyModel ();
                                                                          currentCondition.setPrescNo (prescNo);
                                                                          currentCondition.setRcptNo (null);
                                                                          RecipeFeeBusiness.closeWindow (currentCondition,
                                                                                                         prescField);
                                                                      }

                                                                  });
    }

    private RecipeFeeBusiness ()
    {
    }

    private static void queryByCondition (final RecipeFeeMainPanel mainpanel, final Map <String, Object> map)
    {

        RecipeFeeBusiness.S_RECIPE_FEE_RPC_ASYNC.getPrescByPrescNoOrCardNo (map, new AsyncCallback <ResultModel> ()
        {

            @Override
            public void onFailure (final Throwable caught)
            {
                mainpanel.unmask ();
                ClientUtils.alertMessageBox (caught.getMessage (), mainpanel.getFields ().getRecipeNoField ());
                return;

            }

            @Override
            public void onSuccess (final ResultModel result)
            {
                mainpanel.unmask ();
                if (result == null)
                {
                    // 验证是不满足条件还是没有数据
                    /*RecipeFeeBusiness.verifyPresc (map.get ("condition") + "", mainpanel.getFields ()
                                                                                        .getRecipeNoField ());
*/                  ClientUtils.alertMessageBox ("没有查到处方信息，请重新输入", mainpanel.getM_fields ().getRecipeNoField ()) ;
                    return;
                }
                // 判断是刷卡还是通过处方号来查询
                if ("1".equals (map.get ("flag") + ""))
                {
                    // 展示患者信息
                    mainpanel.setPatientInfoModel (result.getPatientInfoModel ());
                    RecipeFeeUtils.initPatientData (result.getPatientInfoModel (), mainpanel.getFields ());
                }
                mainpanel.getRecipePanel ().getGrid ().getStore ().removeAll ();
                mainpanel.getPrescDetailGrid ().getGrid ().getStore ().removeAll ();
                mainpanel.getRecipePanel ().getGrid ().getStore ().add (result.getPdsPrescDetailInfoModellist ());
                // mainpanel.getM_fields ().getPrescSource ().setValue
                // (prescdetails.get (0).getPrescSourceName ());
                // 默认选择第一条记录
                mainpanel.getRecipePanel ().getCheckmodel ().select (0, true);
                mainpanel.getConfirmBtn ().focus ();
                
            }
        });
    }

    public static void cancelPrescDetail (RecipeFeeMainPanel mainPanel)
    {
        ListStore <PdsPrescDetailInfoModel> detailstore = mainPanel.getPrescDetailGrid ().getGrid ().getStore ();
        List <PdsPrescDetailInfoModel> prescs = mainPanel.getRecipePanel ().getCheckmodel ().getSelectedItems ();
        if (prescs.isEmpty ())
        {
            detailstore.removeAll ();
            return;
        }
        List <PdsPrescDetailInfoModel> prescDetails = detailstore.getModels ();
        Map <String, Object> map = new HashMap <String, Object> ();
        for (PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescs)
        {
            map.put (pdsPrescDetailInfoModel.getPrescNo (), pdsPrescDetailInfoModel);
        }
        for (PdsPrescDetailInfoModel pdsPrescDetailInfoModel : prescDetails)
        {
            if (!map.containsKey (pdsPrescDetailInfoModel.getPrescNo ()))
            {
                detailstore.remove (pdsPrescDetailInfoModel);
            }
        }
    }
}
